package com.bayss.web.interceptor;

import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.util.JsoupUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class AccessHandlerInteceptor implements HandlerInterceptor {
    private static Logger logger = LogManager.getLogger();
    //原来的字符串
//    private static String xssStr = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+";
    //我西药替换的字符串
    private static String xssStr = "insert|select|delete|update";

    /**
     * controller 执行之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否需要进行xss清理
        Enumeration<String> parameterNames = request.getParameterNames();

        while (parameterNames.hasMoreElements()) {
            String name = parameterNames.nextElement();
            String[] values = request.getParameterValues(name);
            for (String value : values) {
                logger.info("params:" + name + "=" + value);
                // xss拦截
                if (judgeSQLInject(value.toLowerCase()) || !JsoupUtil.isValid(name) || !JsoupUtil.isValid(value)) {
                    logger.error("xss拦截:传入参数含有非法字符:{}={}", name, value);
                    throw new DokoServerException(DokoServerExceptionFactor.PARAM_VERIFY_FAIL);
                }
            }
        }
        return true;
    }

    /**
     * controller 执行之后，且页面渲染之前调用
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    /**
     * 页面渲染之后调用，一般用于资源清理操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }


    /**
     * 判断参数是否含有攻击串
     * @param value
     * @return
     */
    public static boolean judgeSQLInject(String value){
        if(value == null || "".equals(value)){
            return false;
        }
        String[] xssArr = xssStr.split("\\|");
        for(int i=0;i<xssArr.length;i++){
            if(value.indexOf(xssArr[i])>-1){
                return true;
            }
        }
        return false;
    }
}
